package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
	"time"
)

var ClearLog = &cobra.Command{
	Use:   "clear_log",
	Short: "清理日志",
	Long:  "清理日志",
	Run: func(cmd *cobra.Command, args []string) {
		if Date != "" {
			if !CheckDate() {
				fmt.Printf("%s时间格式错误，例子：2024-10-01", Date)
				return
			}
		}
		ClearLogFunc()
	},
}

var (
	Date string
	Day  int
	Path string
)

func init() {
	ClearLog.Flags().StringVarP(&Date, "date", "d", "", "清理日期，格式为：yyyy-mm-dd")
	ClearLog.Flags().IntVarP(&Day, "day", "n", 0, "清理几天前的数据")
	ClearLog.Flags().StringVarP(&Path, "path", "p", "", "清理路径")
	RootCmd.AddCommand(ClearLog)
}

func ClearLogFunc() {

	pathInfo, err := os.Stat(Path)
	if err != nil {
		fmt.Println(err)
		return
	}

	if !pathInfo.IsDir() {
		fmt.Println("path is not dir")
		return
	}

	count := 0
	total := 0

	filepath.Walk(Path, func(path string, info os.FileInfo, err error) error {
		fileTime := info.ModTime()
		fmt.Println(path)
		total++
		if Date != "" {
			date, _ := time.Parse("2006-01-02", Date)
			if fileTime.Before(date) {
				err = os.Remove(path)
				if err == nil {
					count++
				}
			}
			return nil
		}

		if Day > 0 && fileTime.Before(time.Now().AddDate(0, 0, -Day)) {
			err = os.Remove(path)
			if err == nil {
				count++
			}
			return nil
		}

		err = os.Remove(path)
		if err == nil {
			count++
		}
		return nil
	})
	tmp, _ := filepath.Abs(Path)
	fmt.Printf("路径：%s，清理完成，共查询%d个文件，共%d个文件被清理\n", tmp, total, count)
}

func CheckDate() bool {
	_, err := time.Parse("2006-01-02", Date)
	return err == nil
}
